package com.a3dweijing.wetouch2.Activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.a3dweijing.wetouch2.Common.CallBack;
import com.a3dweijing.wetouch2.Common.RefreshRecycler.CommonrRecyclerAdapter;
import com.a3dweijing.wetouch2.Common.RefreshRecycler.RefreshLinstener;
import com.a3dweijing.wetouch2.Common.RefreshRecycler.ViewHolder;
import com.a3dweijing.wetouch2.R;
import com.a3dweijing.wetouch2.Util.GlideUtil;
import com.a3dweijing.wetouch2.network.RetrofitUtil;
import com.a3dweijing.wetouch2.Util.Util;
import com.a3dweijing.wetouch2.base.BaseActivity;
import com.a3dweijing.wetouch2.bean.Goodlistitem;
import com.a3dweijing.wetouch2.bean.GoodsInfoBean;
import com.a3dweijing.wetouch2.constant.Api;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class GoodsListViewActivity extends BaseActivity
{
    
    @BindView(R.id.back)
    ImageView back;
    
    @BindView(R.id.top_text)
    TextView topText;
    
    @BindView(R.id.top_right)
    TextView topRight;
    
    @BindView(R.id.top_all)
    RelativeLayout topAll;
    
    @BindView(R.id.rl_new)
    RelativeLayout rlNew;
    
    @BindView(R.id.rl_money)
    RelativeLayout rlMoney;
    
    @BindView(R.id.rl_num)
    RelativeLayout rlNum;
    
    @BindView(R.id.resaut_status_img)
    ImageView resautStatusImg;
    
    @BindView(R.id.resaut_status)
    LinearLayout resautStatus;
    
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    
    @BindView(R.id.tv_new)
    TextView tvNew;
    
    @BindView(R.id.tv_money)
    TextView tvMoney;
    
    @BindView(R.id.tv_num)
    TextView tvNum;
    
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    
    @BindView(R.id.loading_date)
    LinearLayout loadingDate;
    
    private MyAdapter adapter;
    
    ArrayList<GoodsInfoBean> list;
    
    // /**/-1表示所有类型
    private int classid;
    
    // 1代表最新，2代表价格高到低，3代表价格低到高，4代表销量
    private int dors = 1;
    
    private String name;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_list_view);
        ButterKnife.bind(this);
        int id = getIntent().getIntExtra("id", -1);
        name = getIntent().getStringExtra("name");
        classid = id;
        initView();
        initDate(-1 + "", true, true);
        onClick();
    }
    
    private void onClick()
    {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
        {
            @Override
            public void onRefresh()
            {
                initDate(-1 + "", false, true);
            }
        });
        
        recyclerView.addOnScrollListener(new RefreshLinstener(new CallBack()
        {
            @Override
            public void doNext(int what, Object obj)
            {
                if (dors == 1)
                {
                    int id = list.get(0).getS_goods_id();
                    for (GoodsInfoBean goodsListBean : list)
                    {
                        if (id > goodsListBean.getS_goods_id())
                            id = goodsListBean.getS_goods_id();
                    }
                    initDate(id + "", false, false);
                }
                else if (dors == 2)
                {
                    String id = list.get(0).getS_price();
                    for (GoodsInfoBean goodsInfoBean : list)
                    {
                        int i = id.compareTo(goodsInfoBean.getS_price());
                        if (i > 0)
                        {
                            id = goodsInfoBean.getS_price();
                        }
                    }
                    initDate(id, false, false);
                }
                else if (dors == 3)
                {
                    String id = list.get(0).getS_price();
                    for (GoodsInfoBean goodsInfoBean : list)
                    {
                        int i = id.compareTo(goodsInfoBean.getS_price());
                        if (i < 0)
                        {
                            id = goodsInfoBean.getS_price();
                        }
                    }
                    initDate(id, false, false);
                }
                else if (dors == 4)
                {
                    int id = list.get(0).getS_goods_sell_num();
                    for (GoodsInfoBean goodsListBean : list)
                    {
                        if (id > goodsListBean.getS_goods_sell_num())
                            id = goodsListBean.getS_goods_sell_num();
                    }
                    initDate(id + "", false, false);
                }
            }
        }));
    }
    
    public static void startActivity(Activity activity, int classid, String name)
    {
        Intent intent = new Intent();
        intent.putExtra("id", classid);
        intent.putExtra("name", name);
        intent.setClass(activity, GoodsListViewActivity.class);
        activity.startActivity(intent);
    }
    
    private void initDate(String goodid, boolean isshow, final boolean isclear)
    {
        if (isshow)
        {
            loadingDate.setVisibility(View.VISIBLE);
        }
        resautStatus.setVisibility(View.GONE);
        Api api = RetrofitUtil.getInstance().getApiOfPhp();
        Observable<Goodlistitem> observable;
        if (classid == -1)
            observable = api.getListViewAllDate(dors, goodid);
        else
            observable = api.goodsListviewDate(dors, classid, goodid);
        Observer<Goodlistitem> observer = new Observer<Goodlistitem>()
        {
            @Override
            public void onSubscribe(Disposable d)
            {
                disposables.add(d);
            }

            @Override
            public void onNext(Goodlistitem goodlistitem)
            {
                if (goodlistitem.isFlag() && goodlistitem.getGoodsList() != null && goodlistitem.getGoodsList().size() > 0)
                {
                    if (isclear)
                        list.clear();
                    ArrayList<GoodsInfoBean> goodsList = (ArrayList<GoodsInfoBean>)goodlistitem.getGoodsList();
                    list.addAll(goodsList);
                    adapter.notifyDataSetChanged();
                }
                else if (goodlistitem.isFlag()
                        && (goodlistitem.getGoodsList() == null || goodlistitem.getGoodsList().size() == 0))
                {
                    Toast.makeText(GoodsListViewActivity.this, "没有新数据了", Toast.LENGTH_SHORT).show();
                    if (list.size() == 0)
                        resautStatus.setVisibility(View.VISIBLE);

                }
                else
                {
                    resautStatus.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(Throwable e)
            {
                loadingDate.setVisibility(View.GONE);
                resautStatus.setVisibility(View.VISIBLE);
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onComplete()
            {
                loadingDate.setVisibility(View.GONE);
                swipeRefreshLayout.setRefreshing(false);
            }
        };
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(observer);
    }
    

    
    private void initView()
    {
        if (TextUtils.isEmpty(name))
        {
            topText.setText("商品列表");
        }
        else
            topText.setText(name);
        list = new ArrayList<>();
        adapter = new MyAdapter(this, list);
        recyclerView.setLayoutManager(new GridLayoutManager(GoodsListViewActivity.this, 2));
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration()
        {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state)
            {
                // 不是第一个的格子都设一个左边和底部的间距
                outRect.left = 20;
                outRect.bottom = 20;
                // 由于每行都只有3个，所以第一个都是3的倍数，把左边距设为0
                if (parent.getChildLayoutPosition(view) % 2 == 0)
                {
                    outRect.left = 0;
                }
            }
        });
    }
    
    class MyAdapter extends CommonrRecyclerAdapter
    {
        public MyAdapter(Context context, List datas)
        {
            super(context, datas);
        }
        
        @Override
        public void convert(RecyclerView.ViewHolder holder, Object o)
        {
            final GoodsInfoBean goodsListBean = (GoodsInfoBean)o;
            ViewHolder holder1 = (ViewHolder)holder;
            View view = holder1.getView(R.id.parent_rl);
            ImageView imageView = holder1.getView(R.id.img_item);
            TextView itemName = holder1.getView(R.id.item_name);
            TextView moneyItem = holder1.getView(R.id.money_item);
            TextView num = holder1.getView(R.id.num);
            view.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View view)
                {
                    ShoppingDetailsActivity.startActivity(GoodsListViewActivity.this, goodsListBean.getS_goods_id());
                }
            });
            String s = GlideUtil.getInstance().checkUrl(goodsListBean.getS_goods_img_url());
            GlideUtil.getInstance().showImage(GoodsListViewActivity.this, s, imageView);
            itemName.setText(goodsListBean.getS_goods_name());
            moneyItem.setText("￥：" + goodsListBean.getS_price());
            num.setText("销量：" + goodsListBean.getS_goods_sell_num());
        }
        
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
        {
            return ViewHolder.get(GoodsListViewActivity.this, parent, R.layout.goodslistview_item, 0);
        }
    }
    
    private void select()
    {
        Drawable nav_d = getResources().getDrawable(R.drawable.xia);
        nav_d.setBounds(0, 0, nav_d.getMinimumWidth(), nav_d.getMinimumHeight());
        Drawable nav_up = getResources().getDrawable(R.drawable.shang);
        nav_up.setBounds(0, 0, nav_d.getMinimumWidth(), nav_up.getMinimumHeight());
        switch (dors)
        {
            case 1:
                tvNew.setCompoundDrawables(null, null, nav_d, null);
                tvMoney.setCompoundDrawables(null, null, null, null);
                tvNum.setCompoundDrawables(null, null, null, null);
                break;
            case 2:
                tvNew.setCompoundDrawables(null, null, null, null);
                tvMoney.setCompoundDrawables(null, null, nav_d, null);
                tvNum.setCompoundDrawables(null, null, null, null);
                break;
            case 3:
                tvNew.setCompoundDrawables(null, null, null, null);
                tvMoney.setCompoundDrawables(null, null, nav_up, null);
                tvNum.setCompoundDrawables(null, null, null, null);
                break;
            case 4:
                tvNew.setCompoundDrawables(null, null, null, null);
                tvMoney.setCompoundDrawables(null, null, null, null);
                tvNum.setCompoundDrawables(null, null, nav_d, null);
                break;
        }
    }
    
    @OnClick({R.id.rl_new, R.id.rl_money, R.id.rl_num, R.id.back})
    public void onViewClicked(View view)
    {
        if (!Util.isFastClick())
            return;
        switch (view.getId())
        {
            case R.id.rl_new:
                dors = 1;
                select();
                initDate(-1 + "", true, true);
                break;
            case R.id.rl_money:
                if (dors == 2)
                {
                    dors = 3;
                }
                else
                    dors = 2;
                select();
                initDate(-1 + "", true, true);
                break;
            case R.id.rl_num:
                dors = 4;
                select();
                initDate(-1 + "", true, true);
                break;
            case R.id.back:
                finish();
                break;
            
        }
    }
}
